import { UtilsHelper } from "utils/position/UtilsHelper";
import { ActionBase, ActionBaseOfCreep } from "../ActionBase";
import { EActionCode } from "framework/FSM/Action/ActionCode";
/**
 * 红绿一体机 攻击行为
 */
export class ActionCreepDefend  extends ActionBaseOfCreep<IActionCMD<"creepdefend">>
{
    protected updateArgs(action: IActionCMD<"creepdefend">): EActionCode 
    {
        if(super.updateArgs(action) !== EActionCode.OK)
        {
            return EActionCode.FAILED;
        }
        const tactic = action.arg.entity.getTactic();
        action.arg.enemy = Game.getObjectById((tactic as IDefendTactic).enemy[0])!
        return EActionCode.OK;
    }
    protected _execute(action: IActionCMD<"creepdefend">): ActionCode 
    {
        
        const creep = action.arg.entity;
        const hostileCreeps:Creep[]=[action.arg.enemy as Creep];
        const attack_bodys = _.sum(hostileCreeps,e=>e.getActiveBodyparts(RANGED_ATTACK));
        let range = 1;
        if(attack_bodys>=20)
        {
            range=3
        }
        const plancache = creep.room.getWorld().PollBlueplan(creep.room.name);
        if(!plancache)
        {
            return EActionCode.OK;
        }
        const _closeest = _.min(hostileCreeps,e=>e.pos.distance(creep.pos))
        const movepos = plancache.findDefendPosition(_closeest.pos);
        
        {
            // 敌方单位距离我3以上，或者我不在rampart内
            if(movepos)
            {
                if(_closeest.pos.distance(creep.pos)>range || !plancache.isInDefendRampart(creep.pos) || movepos.distance(_closeest.pos)<=1)
                {
                    if(creep.pos.distance(movepos)>0 && creep.pos.distance(_closeest.pos)>1)
                    {
                        creep.mymoveTo({pos:movepos,range:0},{IsUseSafeRegion:plancache.isInSafeRagion(creep.pos)});
                        
                    }
                }

            }
            else
            {
                if(creep.pos.distance(_closeest.pos)>0)
                {
                    creep.mymoveTo({pos:_closeest.pos,range:1},{IsUseSafeRegion:plancache.isInSafeRagion(creep.pos)});
                }
            }
        }
        if(_closeest.pos.distance(creep.pos)<=1)
        {
            creep.attack(_closeest);
        }
        else 
        {
            const obj = creep.pos.findClosestByRange(FIND_HOSTILE_CREEPS);
            if(obj && obj.pos.distance(creep.pos)<=1)
            {
                creep.attack(obj);
            }
        }
        
        return EActionCode.RUNNING;
    }
}